from django.shortcuts import render
from django.views import View
from django import http
from apps.users.models import User, Address
import json
import re
import logging
from django.core.mail import send_mail
from apps.goods.models import SKU
from apps.users.utils import generate_email_verify_url, check_email_verify_url
from celery_tasks.email.tasks import send_email_verify_url
from django.contrib.auth import login, authenticate, logout
from django_redis import get_redis_connection
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from apps.carts.utils import merge_cart_cookie_to_redis

# Create your views here.

#日志输出器
logging = logging.getLogger('django')


class UserBrowseHistory(LoginRequiredJSONMixin, View):
    """用户浏览记录"""
    def get(self, request):
        """获取用户浏览记录"""
        user_id = request.user.id
        #redis对象
        redis_conn = get_redis_connection('history')

        #获取数据
        skus_id_list = redis_conn.lrange('history_%s' %user_id, 0, -1)

        #in: 查询指定范围内的数据
        #sku = SKU.objects.filter(id__in=skus_id_list)
        #filter()搭配in范围查询时默认会按照主键字段从小到大排序

        #sku数据转字典列表
        skus = []
        for i in skus_id_list:
            sku = SKU.objects.get(id=i)
            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'OK',
                                  'skus': skus})


    def post(self, request):
        """保存用户浏览记录
        POST请求地址/browse_histories/
        """
        #接受参数
        data_dict = json.loads(request.body.decode())
        sku_id = data_dict.get('sku_id')

        # 检验参数
        try:
            SKU.objects.get(id=sku_id)

        except SKU.DoesNotExist:
            return http.JsonResponse({'code': 400,
                                  'errmsg': 'sku_id不存在'})

        #实现核心逻辑:保存数据到redis数据库
        user_id = request.user.id
        redis_conn = get_redis_connection('history')

        #使用管道
        pl = redis_conn.pipeline()
            #去重
        pl.lrem('history_%s' %user_id, 0, sku_id)

            #添加
        pl.lpush('history_%s' %user_id, sku_id)

            #截取
        pl.ltrim('history_%s' %user_id, 0, 4)

        #执行管道
        pl.execute()

        #响应结果
        return http.JsonResponse({'code':0,
                                  'errmsg':'ok'})



class ChangePasswordView(LoginRequiredJSONMixin, View):
    """修改密码
    PUT请求地址	/password/
    """
    def put(self, request):
        """实现修改密码逻辑"""
        # 接收参数
        data_dict = json.loads(request.body.decode())
        old_password = data_dict.get('old_password')
        new_password = data_dict.get('new_password')
        new_password2 = data_dict.get('new_password2')

        #检验参数
        if not all([old_password, new_password, new_password2]):
            return http.JsonResponse({'code':400,
                                     'errmsg':'缺少必传参数'})

        # 判断密码是否正确
        result = request.user.check_password(old_password)
        if not result:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '两次输入密码不一致'})

        # 实现核心逻辑
        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()

        except Exception as e:
            logging.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '密码修改失败'})

        # 清理状态保持信息
        logout(request)

        response = http.JsonResponse({'code': 0,
                                      'errmsg': 'ok'})

        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response


class UpdateTitleAddressView(View):
    """设置地址标题"""

    def put(self, request, address_id):
        """设置地址标题
        PUT请求地址/addresses/(?P<address_id>\d+)/title/
        """
        # 接收参数：地址标题
        data_dict = json.loads(request.body.decode())
        title = data_dict.get('title')

        #修改title
        try:
            address = Address.objects.get(id= address_id)
            address.title = title
            address.save()
        except Exception as e:
            logging.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '设置地址标题失败'})

        #响应结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '设置地址标题成功'})


class DefaultAddressView(LoginRequiredJSONMixin, View):
    """设置默认地址
    PUT请求地址/addresses/(?P<address_id>\d+)/default/
    """

    def put(self, request, address_id):
        """设置默认地址"""
        #接受参数查询地址
        try:
            address = Address.objects.get(id= address_id)

            #设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logging.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '设置默认地址失败'})

        #响应结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '设置默认地址成功'})


class UpdateDestroyAddressView(LoginRequiredJSONMixin, View):
    """修改和删除地址"""

    def put(self, request, address_id):
        """修改地址
        /addresses/(?P<address_id>\d+)/
        """
        #获取参数
        data_dict  =json.loads(request.body.decode())
        receiver = data_dict.get('receiver')
        province_id = data_dict.get('province_id')
        city_id = data_dict.get('city_id')
        district_id = data_dict.get('district_id')
        place = data_dict.get('place')
        mobile = data_dict.get('mobile')
        tel = data_dict.get('tel')
        email = data_dict.get('email')

        #校验参数
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})

        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})

        # 判断地址是否存在,并更新地址信息
        try:
            address = Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logging.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '更新地址失败'})

        #构造响应数据
        address_dict= {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        #响应结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '更新地址成功',
                                  'address': address_dict})


    def delete(self, request, address_id):
        """删除地址
        /addresses/(?P<address_id>\d+)/
        """
        try:
            address = Address.objects.get(id=address_id)
            address.is_deleted = True
            address.save()

        except Exception as e:
            logging.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '删除地址失败'})

        # 响应删除地址结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '删除地址成功'})


class AddressView(LoginRequiredJSONMixin, View):
    """用户收货地址
    GET	/addresses/
    """
    def get(self, request):
        """提供地址管理界面
        """
        #获取逻辑删除的地址查询集
        addresses_data = request.user.addresses.filter(is_deleted=False)
        # if not addresses_data:
        #     return http.JsonResponse({'code': 400,
        #                               'errmsg': '的撒多撒上限'})
        #查询当前登录用户的默认id
        default_address_id = request.user.default_address_id

        # 构造响应数据
        addresses_dict_list = []
        for i in addresses_data:
            addresses_dict = {
                "id": i.id,
                "title": i.title,
                "receiver": i.receiver,
                "province": i.province.name,
                "city": i.city.name,
                "district": i.district.name,
                "place": i.place,
                "mobile": i.mobile,
                "tel": i.tel,
                "email": i.email
            }
            addresses_dict_list.append(addresses_dict)

        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'default_address_id': default_address_id,
                                  'addresses': addresses_dict_list})


class CreateAddressView(LoginRequiredJSONMixin, View):
    """新增地址
    POST/addresses/create/
    """
    def post(self, request):
        """实现新增地址逻辑"""
        #判断地址是否超过20:一方模型对象.多方模型类名拼接_set,
        #一方模型对象.多方自定义related_name名:request.user.addresses
        count = request.user.addresses.filter(is_deleted=False).count()
        if count >= 20:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '地址超过数量上限'})

        #接受参数
        data_dict = json.loads(request.body.decode())
        receiver = data_dict.get('receiver')
        province_id = data_dict.get('province_id')
        city_id = data_dict.get('city_id')
        district_id = data_dict.get('district_id')
        place = data_dict.get('place')
        mobile = data_dict.get('mobile')
        tel = data_dict.get('tel')
        email = data_dict.get('email')

        #校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})

        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})

        #实现核心代码
        try:
            address = Address.objects.create(
                user=request.user,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                title = receiver,  #默认标题就是收件人
                receiver = receiver,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )
            #新增地址时给用户绑定默认地址request.user:当前登录用户
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception as e:
            logging.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '新增地址失败'})

        #构造响应数据
        address_dict= {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        #响应结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '新增地址成功',
                                  'address': address_dict})


class EmailActiveView(View):
    """
    POU/email/verification/
    """
    def put(self,request):
        #接受参数
        token = request.GET.get('token')

        #检验参数
        if not token:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        #实现核心逻辑
            #通过token提取要验证邮箱的用户
        user = check_email_verify_url(token=token)

            #将要验证邮箱的用户的email_active设置为true
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logging.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '邮箱验证失败'})

        #响应结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '邮箱验证ok'})


class EmailView(LoginRequiredJSONMixin,View):
    """添加邮箱
    put/emails/
    """
    def put(self, request):
        """实现添加邮箱的逻辑"""
        #接受参数
        data_dict = json.loads(request.body.decode())
        email = data_dict.get('email')

        #校验参数
        if not email:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        #判断邮箱格式
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'email格式错误'})

        #实现核心逻辑
            #添加邮箱到数据库
        try:
           request.user.email = email
           request.user.save()
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '添加email失败'})

        #发送邮箱的验证激活邮件
        # send_mail()耗时操作异步处理
        # send_email_verity_url.delay(email,'激活链接')
        verify_url = generate_email_verify_url(user=request.user)
        send_email_verify_url(email, verify_url)

        # 响应结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok'})


class UserInfoView(LoginRequiredJSONMixin, View):
    #用户中心
    def get(self,request):
        #Django帮助我们拿着session中提取的user_id,去数据库查询出来user,并赋值给request.user属性
        #如果该接口只有登录用户可以访问,那么在接口内部可以直接使用request.user获取当前登录用户信息
        #is_authenticated属性判断是否登录
        data_dict = {
            'code':0,
            'errmsg':'ok',
            'info_data':{
                'username':request.user.username,
                'mobile':request.user.mobile,
                'email':request.user.email,
                'email_active':request.user.email_active
            }
        }

        return http.JsonResponse(data_dict)


class LogoutView(View):
    #退出登录
    def delete(self, request):

        #清理登录状态
        logout(request)
        #清理用户名
        response = http.JsonResponse({'code':0,
                                      'errmsg':'退出登录ok'})
        response.delete_cookie('username')

        return response


class LoginView(View):
    #用户登录
    def post(self, request):
        """
        :param request:
        :return:
        username  用户名
        password  密码
        remembered  是否记住用户
        """
        #接受参数
        user_dict = json.loads(request.body.decode())
        account = user_dict.get('username')
        password = user_dict.get('password')
        remembered = user_dict.get('remembered')

        #校验参数
        if not all([account, password]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        # 判断用户名格式是否符合
        # if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', account):
        #     return http.JsonResponse({'code': 400,
        #                               'errmsg': '用户名格式不符'})

        # 判断密码格式是否符合
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '密码格式不符'})

        #实现多账号登录
        # 判断是手机号还是用户名指定USERNAME_FIELD=mobile
        if re.match(r'^1[3-9]\d{9}$', account):
            User.USERNAME_FIELD = 'mobile'
        #实现核心逻辑
            #判断用户是否是注册用户Django封装好了一个方法来认证
            # 如果是注册用户校验数据库参数是否一致
        user = authenticate(request=request, username=account, password=password)

        # 判断用户名认证是否成功
        if not user:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '用户名或密码错误'})

        #实行状态保持
        login(request, user)
        #根据remembered来判断设置状态保持周期
        if remembered != True:
            request.session.set_expiry(0)

        else:
            #None表示默认两周时间
            request.session.set_expiry(None)

        #注册成功后用户名写入cookie
        response = http.JsonResponse({'code': 0,
                                  'errmsg': 'ok'})
        response.set_cookie('username', user.username, max_age=3600*24*14)

        #合并购物车
        #from apps.carts.utils import merge_cart_cookie_to_redis
        response =  merge_cart_cookie_to_redis(request, user, response)

        #响应结果
        return response


class UserRegisterView(View):
    # 用户注册
    def post(self, request):
        # 提取request数据并转换为字典类型
        user_sq = request.body
        user_bd = user_sq.decode()
        user_dict = json.loads(user_bd)

        # 获得数据
        username = user_dict.get('username')
        password = user_dict.get('password')
        password2 = user_dict.get('password2')
        mobile = user_dict.get('mobile')
        #提取短信参数
        sms_code_client = user_dict.get('sms_code')
        allow = user_dict.get('allow')

        # 进行校验判断是否缺少必传参数
        if not all([username, password, password2,mobile, allow]):
            return http.JsonResponse({'code':400,
                                      'errmsg':'缺少必传参数'})

        # 判断用户名格式是否符合
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '用户名格式不符'})

        #判断密码格式是否符合
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '密码格式不符'})

        #判断二次密码是否一样
        if password!=password2:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '两次输入密码不一样'})

        #判断手机号是否符合
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code':400,
                                      'errmsg':'手机号格式错误'})

        #判断短信验证码是否正确
        #判断服务的短信是否存在,提取数据库短信
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if not sms_code_server:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '短信验证码失效'})

        if sms_code_server.decode() != sms_code_client:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '短信验证码错误'})

        #判断是否勾选协议
        if allow !=True:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '协议未勾选'})

        #保存数据到注册表使用django提供的create_user
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)

        except Exception as e:

            logging.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '注册失败'})

        #实行状态保持login是Django封装的进行状态保持
        login(request, user)

        # 注册成功后用户名写入cookie
        response = http.JsonResponse({'code': 0,
                                      'errmsg': 'ok'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        # 合并购物车
        from apps.carts.utils import merge_cart_cookie_to_redis
        response = merge_cart_cookie_to_redis(request, user, response)

        # 响应结果
        return response


class UsernameCountView(View):
    """判断用户名是否重复注册
    http://www.meiduo.site:8000/username/itcast/count/
    """
    def get(self, request, username):
        '''判断用户名是否重复
        usernames/itcasa/count
        '''
        # 1.查询username在数据库中的个数
        # User.objects.filter(username='用户名').count()
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                 'errmsg': '访问数据库失败'})

            # 2.返回结果(json) ---> code & errmsg & count
        return http.JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'count': count})


class UserMobileCountView(View):
    """判断手机号是否注册"""
    # / mobiles / (?P < mobile > 1[3-9]\d{9}) / count /
    def  get(self, request, mobile):
        # count = User.objects.filter(mobiles='手机号').count()
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'ok',
                                      })
        return http.JsonResponse({'code': 0,
                                      'errmsg': 'ok',
                                      'count': count})

